package com.lmq.wxshare.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmq.wxshare.common.HttpRequest;
import com.lmq.wxshare.common.WXCommon;
import com.lmq.wxshare.entity.AccessToken;
import com.lmq.wxshare.mapper.AccessTokenMapper;
import com.lmq.wxshare.service.AccessTokenService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

@Service
public class AccessTokenServiceImpl extends ServiceImpl<AccessTokenMapper, AccessToken> implements AccessTokenService {

    @Value("${wx.accesstoken}")
    private String access_token_url;

    @Value("${wx.appID}")
    private String appID;

    @Value("${wx.appsecret}")
    private String appsecret;

    @Value("${wx.js_api}")
    private String jsapi_url;

    @Override
    public AccessToken getAccessToken() {
        List<AccessToken> list = baseMapper.selectList(null);
        AccessToken token = null;
        String access_token;
        if(list!=null && list.size()>0){
            token = list.get(0);
            if(token.getJsValidDate()>new Date().getTime()){
                return token;
            }
            if(token.getAccessValidDate()>new Date().getTime()){
                access_token = token.getAccessToken();
                String jsapiUrl = jsapi_url.replace("ACCESS_TOKEN", access_token);
                String jsResult = HttpRequest.sendGet(jsapiUrl, null);
                JSONObject jsObject = JSONObject.parseObject(jsResult);
                token.setJsapiTicket(jsObject.getString("ticket"));
                token.setJsValidDate(new Date().getTime()+7200000);
                baseMapper.updateById(token);
            }else{
                String accessTokenUrl = access_token_url.replace("APPID", appID).replace("APPSECRET", appsecret);
                String result = HttpRequest.sendPost(accessTokenUrl, null);
                JSONObject accessObject = JSONObject.parseObject(result);
                token.setAccessToken(accessObject.getString("access_token"));
                token.setAccessValidDate(new Date().getTime()+7200000);

                String jsapiUrl = jsapi_url.replace("ACCESS_TOKEN", accessObject.getString("access_token"));
                String jsResult = HttpRequest.sendPost(jsapiUrl, null);
                JSONObject jsObject = JSONObject.parseObject(jsResult);
                token.setJsapiTicket(jsObject.getString("ticket"));
                token.setJsValidDate(new Date().getTime()+7200000);
                //System.out.println("#############################:"+token.getAccessValidDate());
                baseMapper.updateById(token);
            }
        }else{
            token = new AccessToken();
            String accessTokenUrl = access_token_url.replace("APPID", appID).replace("APPSECRET", appsecret);
            String result = HttpRequest.sendPost(accessTokenUrl, null);
            JSONObject accessObject = JSONObject.parseObject(result);
            token.setAccessToken(accessObject.getString("access_token"));
            token.setAccessValidDate(new Date().getTime()+7200000);

            String jsapiUrl = jsapi_url.replace("ACCESS_TOKEN", accessObject.getString("access_token"));
            String jsResult = HttpRequest.sendPost(jsapiUrl, null);
            JSONObject jsObject = JSONObject.parseObject(jsResult);
            token.setJsapiTicket(jsObject.getString("ticket"));
            token.setJsValidDate(new Date().getTime()+7200000);
            //System.out.println("#############################:"+token.getAccessValidDate());
            baseMapper.insert(token);
        }
        return token;
    }

    @Override
    public String getSignature(AccessToken token, String noncestr, String timestamp, String url) {
        StringBuffer value = new StringBuffer();
        value.append("jsapi_ticket=").append(token.getJsapiTicket()).append("&noncestr=")
                .append(noncestr).append("&timestamp=").append(timestamp).append("&url=")
                .append(url);
        String signature = "";
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(value.toString().getBytes("UTF-8"));
            signature = WXCommon.byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return signature;
    }
}
